/**
** Load script from local or remote location. 
** When the script is loaded - callback function is invoked.
** No prerequirements for this function
**/
function loadScript(url, callback) {
    var script = document.createElement("script")
    script.type = "text/javascript";
    if (script.readyState) { //IE
        script.onreadystatechange = function () {
            if (script.readyState == "loaded" || script.readyState == "complete") {
                script.onreadystatechange = null;
                if(callback!=false) {
                	callback();
                }
            }
        };
    } else { //Others
        script.onload = function () {
	        if(callback!=false) {
	        	callback();	
	        }
        };
    }
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

/**
** Function loads widget (html, js and css) inside JSON object.
** Requires jQuery 
** params:
**	script - url of script which returns JSON: {html:"...", js:"...", css:"..."} 
**	params - parameters which sent to script
**	appendTo - id of element to append html part 
**			Note: 'html' injected into document before 'js' part running
**			so you can use 'html' elements in javascript
**	method - ajax call method (GET/POST)
**
**/
function loadWidget(script, params, appendTo, method) {
	$.ajax({
	  type: method,
	  url: script,
	  dataType : 'text',
	  data : params,
	  error: function(xhr, ajaxOptions, err) {
        console.log("status:" + xhr.status + " err:" + err);
	  }
	}).done(function( msg ) {
		var x = eval("(" + msg + ")");
		if(x.css) {
			var style = document.createElement('style');
			style.type= "text/css";
			if(style.styleSheet) {
				//IE only
				style.styleSheet.cssText= x.css; 
			} else {
				// Non IE
				style.appendChild(document.createTextNode(x.css));
			}
			document.getElementsByTagName('head')[0].appendChild(style);
		}
		
		if (x.html) {
			$("#"+appendTo).append(x.html);
		}
		
		if(x.js) {
			jQuery.globalEval(x.js);
		}
	});
}

function loadWidgetGET(script, params, appendTo) {
	loadWidget(script, params, appendTo, "GET");
}

function loadWidgetPOST(script, params, appendTo) {
	loadWidget(script, params, appendTo, "POST");
}
